#include "encrpty.h"
#include <stdlib.h>

encrpty::encrpty()
{

}

//将strhex中的hex转换成对应的值
int encrpty::strhex_to_strbyte(std::string strhex, std::string &strbyte)
{
    if (strhex.length() % 2 != 0)
        return -1;

    strbyte.clear();
    int len = strhex.length()/2;

    char buf[3] = {0 , 0, 0};
    int pos = 0;
    int i = 0;
    unsigned char tmp = 0;
    for ( ; i < len; i++)
    {
        buf[0] = strhex.at(pos++);
        buf[1] = strhex.at(pos++);
        tmp = (unsigned char)(strtol(buf, NULL, 16) & 0XFF);
        strbyte.push_back(tmp);
    }
    return 0;
}

//将strbyte中的每个字节转换成
int encrpty::strbyte_to_strhex(std::string strbyte, std::string &strhex)
{
    int len = strbyte.length();
    int i = 0;
    char const table [16+1] = "0123456789ABCDEF";
    unsigned char tmp = 0;
    for (;i < len; i++)
    {
        tmp = (unsigned char)strbyte.at(i);
        strhex.push_back(table[(tmp & 0xf0) >> 4]);
        strhex.push_back(table[(tmp & 0xf)]);
    }
    return 0;
}

int encrpty::strencrpty(std::string strsrc, std::string &strdst, unsigned int key)
{
    std::string strbyte ="";
    strhex_to_strbyte(strsrc, strbyte);
    unsigned char keybuf[8];
    keybuf[0] = (key & 0xff000000) >> 24;
    keybuf[1] = (key & 0xff0000) >> 16;
    keybuf[2] = (key & 0xff00) >> 8;
    keybuf[3] = (key & 0xff);
    keybuf[4] = 0xff - keybuf[0];
    keybuf[5] = 0xff - keybuf[1];
    keybuf[6] = 0xff - keybuf[2];
    keybuf[7] = 0xff - keybuf[3];

    int len = strbyte.length();
    int i = 0;
    std::string strencrypt = "";
    unsigned char tmp = 0;
    int pos = 0;
    for (; i < len; i++)
    {
        if (pos > 7)
            pos = 0;
        tmp = strbyte.at(i) ^ keybuf[pos++];
        strencrypt.push_back(tmp);
    }
    strbyte_to_strhex(strencrypt, strdst);
    return 0;
}

int encrpty::decrypted(std::string strsrc, std::string &strdst, unsigned int key)
{
    return strencrpty(strsrc, strdst, key);
}
